import { Message } from 'element-ui'
import axios from 'axios'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://idpdevgateway.lcfuturecenter.com',
  timeout: globalConfig.httpTimeOut,
  // 是否允许携带认证 不允许
  withCredentials: false
})

// 请求拦截-------------------------------------axiosUtils intercept------- //
request.interceptors.request.use(
  request => {
    const authConfig = request.authConfig
    // 发送请求之前
    if (authConfig.downExcelFile) {
      request.responseType = 'arraybuffer'
    }
    request.headers['accesstoken'] = authConfig.token
    return request
  },
  error => {
    // 发送请求错误时
    return Promise.reject(error)
  }
)

// 返回拦截-------------------------------------response intercept------- //
request.interceptors.response.use(
  response => {
    const authConfig = response.config.authConfig
    if (authConfig.downExcelFile) {
      return Promise.resolve(response)
    }
    // 正常响应
    switch (response.data.code) {
      // 自定义code处理
      case 0:
        if (authConfig.msgSuccess) {
          Message({
            message: response.data.message,
            type: 'success',
            duration: 1000
          })
        }
        return Promise.resolve(response.data)
      case 5:
        Message({
          message: response.data.message,
          type: 'error',
          duration: 3000
        })
        return Promise.reject(response.data)
      default:
        if (authConfig.msgError) {
          Message({
            message:
              response.data.message + (response.data.detail === null ? '' : response.data.detail),
            type: 'error',
            duration: 3000
          })
        }
        return Promise.reject(response.data)
    }
  },
  error => {
    // 错误响应
    const errMsg = error.message
    Message({
      message: errMsg,
      type: 'error',
      duration: 1000
    })
    return Promise.reject(error)
  }
)

export function httpGet(url, params, authConfig) {
  return request({
    method: 'get',
    url: url,
    params: params,
    authConfig: authConfig || { msgSuccess: false, msgError: true }
  })
}
//  authConfig {msgSuccess: '',msgError: ''}
export function httpPost(url, data, authConfig) {
  return request({
    method: 'post',
    url: url,
    data: { data: data },
    authConfig: authConfig || { msgSuccess: false, msgError: true }
  })
}

// 原生axios使用 调用参考 http://www.axios-js.com/zh-cn/docs/
